require("../../assets/css/basic.less");
require("../../assets/css/normalize.css");
require("../../assets/css/property.css");
require("../../assets/css/reset.css");
require("../../assets/fonts/font-icon/iconfont.css");

require("../course_play/course_play.less");
const dom = require("../../libs/dom.js");
const axios = require("../../libs/axios.js");

document.addEventListener("DOMContentLoaded", function () {
	// 将数据渲染到页面上
	const fragments = JSON.parse(localStorage.getItem("fragments"));
	let n = 0; //关键点:定义一个变量控制当前播放的节
	let video = dom.get("#video");
	let pro = dom.get(".progress-bar");
	let timer = null;
	let startTime = Date.now(); //进入页面开始计时
	let duration = 0; //持续时间

	// 定义函数,用于播放视频
	function play() {
		dom.get("#playNum").textContent = n + 1;
		dom.get("#numLength").textContent = fragments.length;
		dom.get("#title").textContent = fragments[n].title;
		video.src = axios.defaults.baseURL + fragments[n].videoUrl;
		video.play();

		//进度条
		timer = setInterval(function () {
			pro.style.width = (100 * video.currentTime) / video.duration + "%";
		}, 50);
	}
	play();

	// 播放完当前的,自动播放下一节
	video.addEventListener("ended", function () {
		n++;
		if (n < fragments.length) {
			play();
		} else {
			n = fragments.length - 1;
		}
	});

	// 点击按钮向左跳转到上一节
	dom.get(".icon-shangyiye").addEventListener("click", function () {
		n--;
		if (n < 0) {
			n = 0;
		}
		play();
	});

	// 点击按钮向右跳转到下一节
	dom.get(".icon-xiayiye").addEventListener("click", function () {
		n++;
		if (n >= fragments.length) {
			n = fragments.length - 1;
		}
		play();
	});

	// 隐藏蒙层
	dom.get("#mask").addEventListener("click", function () {
		this.style.display = "none";
		dom.get("#box").style.display = "none";
		video.play();
	});

	// 点击暂停按钮显示蒙层
	dom.get(".icon-iconstop").addEventListener("click", function () {
		dom.get("#mask").style.display = "block";
		dom.get("#box").style.display = "flex";
		video.pause();

		//计算时间
		duration += Date.now() - startTime;
	});

	// 点击蒙层中的继续训练
	dom.get(".icon-bofang").addEventListener("click", function () {
		dom.get("#mask").style.display = "none";
		dom.get("#box").style.display = "none";
		video.play();

		//重新计时
		startTime = Date.now();
	});

	// 结束训练
	dom.get("#ended").addEventListener("click", function () {
		duration = Math.floor(duration / 1000);
		let calorie = Math.ceil(duration * 1.57);

		axios
			.post("/api/exercise/save", {
				type: 2,
				duration,
				calorie,
			})
			.then((res) => {
				if (res.data.errno === 0) {
					alert("训练结束");
					location.href = "course.html";
				}
			});
	});
});
